﻿/***************************************************************************
 *    
 *      Copyright (c) 2009,2010,2011 KaiTrade LLC (registered in Delaware)
 *                     All Rights Reserved Worldwide
 *
 * STRICTLY PROPRIETARY and CONFIDENTIAL
 *
 * WARNING:  This file is the confidential property of KaiTrade LLC For
 * use only by those with the express written permission and license from
 * KaiTrade LLC.  Unauthorized reproduction, distribution, use or disclosure 
 * of this file or any program (or document) is prohibited. 
 * 
 ***************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Timers;

using log4net;
using log4net.Config;

using System.Windows.Forms;
using K2ServiceSupport;

namespace K2RemoteTest
{
    public partial class frmTestApp : Form,  IDisposable
    {

        // This delegate enables asynchronous calls for setting
        // the text property on a TextBox control.
        delegate void SetTextCallback(string text);

        //K2ServiceSupport.K2ServiceClient
        

        private string m_Id = "";

        private string m_LastOrderID = "";

        private List<KaiTrade.TradeObjects.TSDataItem > m_LastBars;

        public frmTestApp()
        {
            InitializeComponent();
            m_LastBars = new List<KaiTrade.TradeObjects.TSDataItem>();
            
        }

        #region Connections
        /// <summary>
        /// Connect to the Server box - sets up WCF Connections
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().ServerAddress = cboServer.Text;
                K2ServiceSupport.K2ServiceClient.Instance().Connect();

                //Add any call back handlers - for example to process prices or bar data
                K2ServiceSupport.K2ServiceClient.Instance().TsdUpdate += new K2ServiceSupport.OnTsdUpdate(OnTsdUpdate);
                K2ServiceSupport.K2ServiceClient.Instance().PxUpdate += new K2ServiceSupport.OnPxUpdate(OnPxUpdate);

                btnSignOn.Enabled = true;
            }
            catch (Exception myE)
            {
            }
        }

        /// <summary>
        /// Sign on as a user to the server, you need to connect before calling this
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSignOn_Click(object sender, EventArgs e)
        {
            try
            {
                string serverId = K2ServiceSupport.K2ServiceClient.Instance().SignOn(txtUserID.Text, txtPwd.Text);
                if (serverId.Length > 0)
                {
                    txtID.Text = serverId;

                    btnSignOff.Enabled = true;
                    btnGetProfile.Enabled = true;
                }
                else
                {
                    txtID.Text = "SignOn Failed";
                }
            }
            catch (Exception myE)
            {

            }
        }

        private void btnSignOff_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().SignOut();
            }
            catch (Exception myE)
            {
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().DisConnect();
                //btnSignOn.Enabled = true;
            }
            catch (Exception myE)
            {
            }
        }

        /// <summary>
        /// Get a users profile XML
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetProfile_Click(object sender, EventArgs e)
        {
            try
            {
                txtConfig.Text = K2ServiceSupport.K2ServiceClient.Instance().GetUserProfile(txtID.Text);
            }
            catch (Exception myE)
            {
            }
        }

        /// <summary>
        /// Get a list of available accounts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetAccounts_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboVenue.Text.Length > 0)
                {
                    cboAccounts.Items.Clear();
                    List<KaiTrade.TradeObjects.Account> accounts = K2ServiceSupport.K2ServiceClient.Instance().GetAccounts(cboVenue.Text);
                    foreach (KaiTrade.TradeObjects.Account account in accounts)
                    {
                        cboAccounts.Items.Add(account.AccountCode);
                    }

                }
            }
            catch (Exception myE)
            {
            }
        }

        #endregion


        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

       
       
       
        

        #region products

        /// <summary>
        /// Get a list of available trade venues
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetVenues_Click(object sender, EventArgs e)
        {
            try
            {
                cboVenue.Items.Clear();
                foreach (KaiTrade.TradeObjects.TradeVenue venue in K2ServiceSupport.K2ServiceClient.Instance().GetVenues())
                {
                    cboVenue.Items.Add(venue.Code);
                }
                
            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Get a list of products for some venue
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetProducts_Click(object sender, EventArgs e)
        {
            try
            {
                cboProducts.Items.Clear();
                foreach (KaiTrade.TradeObjects.ProductData product in K2ServiceSupport.K2ServiceClient.Instance().GetProducts(cboVenue.Text, ""))
                {
                    cboProducts.Items.Add(product.Mnemonic);
                }

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Create a mnemonic in the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetMnemonic_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().CheckCreateMnemonic(txtUserName.Text, cboVenue.Text, txtProductSrc.Text, txtExchange.Text, "", cboCFICode.Text, "USD", "", "");
            }
            catch (Exception myE)
            {
            }
        }


        /// <summary>
        ///  get a products data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetProductData_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().GetProduct(cboProducts.Text);

            }
            catch (Exception myE)
            {
            }
        }


        #endregion


        #region orderprocessing

        /// <summary>
        /// Add a strategy to the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddStraegy_Click(object sender, EventArgs e)
        {
            try
            {
                // Set up a list for any additional strategy parameters
                List<KaiTrade.TradeObjects.K2Parameter> myParms = new List<KaiTrade.TradeObjects.K2Parameter>();
                
                // Add the strategy - note hard coded quite a few of the parameters since this is just an example
                string id = K2ServiceSupport.K2ServiceClient.Instance().AddStrategy(txtStratMenmonic.Text, txtStrategyName.Text, "BUY", "LIMIT", 1, "TESTACT", "KTStandard", myParms);
                
                txtStratID.Text = id;
            }
            catch (Exception myE)
            {
            }
        }


       

        /// <summary>
        /// Register to receive order fills
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRegisterFIlls_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().Subscribe();

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Get a strategy from the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetStrategy_Click(object sender, EventArgs e)
        {
            try
            {
                KaiTrade.TradeObjects.StrategyData strategy = K2ServiceSupport.K2ServiceClient.Instance().GetStrategy(txtStratID.Text);

            }
            catch (Exception myE)
            {

            }

        }

        /// <summary>
        /// Send an enter signal to a strategy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEnter_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().EnterStrategy(txtStratID.Text);

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Send an exit signal to a strategy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExitStrategy_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().ExitStrategy(txtStratID.Text);

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Cancel a strategy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().CancelStrategy(txtStratID.Text);

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Get the ADTL for a strategy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetAtdl_Click(object sender, EventArgs e)
        {
            try
            {
               txtAtdl.Text =  K2ServiceSupport.K2ServiceClient.Instance().GetStrategyAtdl(txtStratID.Text);

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Get a list of Algorithem names
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetAlgoNames_Click(object sender, EventArgs e)
        {
            try
            {
                cboAlgoNames.Items.Clear();
                string[] names = K2ServiceSupport.K2ServiceClient.Instance().GetAvailableORAlgorithmNames();
                foreach (string name in names)
                {
                    cboAlgoNames.Items.Add(name);
                }

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Get an Algorithems ADTL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetAlgoAtdl_Click(object sender, EventArgs e)
        {
            try
            {
                txtAtdl.Text = K2ServiceSupport.K2ServiceClient.Instance().GetORAlgorithmAtdl(cboAlgoNames.Text);

            }
            catch (Exception myE)
            {

            }
        }


        /// <summary>
        /// place an order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOrder_Click(object sender, EventArgs e)
        {
            try
            {

                //K2ServiceSupport.K2ServiceClient.Instance().Order(txtStratID.Text, txtStratMenmonic.Text);
                double qty = double.Parse(txtQty.Text);
                double price = double.Parse(txtPrice.Text);
                List<KaiTrade.TradeObjects.K2Parameter> parameters = new List<KaiTrade.TradeObjects.K2Parameter>();
                m_LastOrderID = K2ServiceSupport.K2ServiceClient.Instance().SubmitOrder(txtOrdrStrategy.Text, txtOrdrMnemonic.Text, qty, price, cboSide.Text, cboOrderType.Text, 1, "DAY", "", txtAccount.Text, "", 1, "", parameters);
                txtLastOrderID.Text = m_LastOrderID;
            }
            catch (Exception myE)
            {
            }
        }

        /// <summary>
        /// Get an order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetOrder_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().GetOrder(txtLastOrderID.Text);

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Get a list of order IDs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetOrderList_Click(object sender, EventArgs e)
        {
            try
            {
                string[] orderList = K2ServiceSupport.K2ServiceClient.Instance().GetOrderList();
                
                foreach (string orderID in orderList)
                {
                }

            }
            catch (Exception myE)
            {

            }

        }

        private void btnGetAllOrders_Click(object sender, EventArgs e)
        {
            try
            {
                KaiTrade.TradeObjects.OrderData[] orders = K2ServiceSupport.K2ServiceClient.Instance().GetAllOrders();
                foreach (KaiTrade.TradeObjects.OrderData o in orders)
                {
                    if (o.OrdStatus == K2ServiceSupport.OrderStatus.FILLED)
                    {
                        // do filled processing
                        double cumQtyFilled = o.CumQty;
                        double lastPx = o.LastPx;
                        // and so on
                    }
                }
            }
            catch (Exception myE)
            {
            }
        }

        /// <summary>
        /// Cancel a working order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOrdCancel_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().CancelOrder(txtLastOrderID.Text);

            }
            catch (Exception myE)
            {

            }
        }

        /// <summary>
        /// Modify a working order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOrdMod_Click(object sender, EventArgs e)
        {
            try
            {

                double? newQty = double.Parse(txtQty.Text);
                double? newPrice = double.Parse(txtPrice.Text);
                double? newStopPx = newPrice;
                K2ServiceSupport.K2ServiceClient.Instance().ReplaceOrder(txtLastOrderID.Text,newQty,newPrice,newStopPx);

            }
            catch (Exception myE)
            {

            }
        }

       

        private void btnSendSignal_Click(object sender, EventArgs e)
        {
            try
            {
                KaiTrade.TradeObjects.TradeSignal signal = new KaiTrade.TradeObjects.TradeSignal();
                signal.Name = "";
                signal.Mnemonic = "KTSIM:ZZ:DELL:ESXXXX";
                signal.OrdQty = 2;
                signal.Side = "BUY";
                signal.OrdType = "LIMIT";
                signal.Price = 22;
                signal.SignalType = KaiTrade.Interfaces.TradeSignalType.enter;
                signal.Set = true;
                 
                K2ServiceSupport.K2ServiceClient.Instance().ProcessTradeSignal("LSTEST", DateTime.Now.Ticks.ToString(), "KTStandard", "MWTrader", "LS1", true, signal);

                //Factory.Instance().AppFacade.ProcessTradeSignal("", "LSTEST", DateTime.Now.Ticks.ToString(), "LSExecAlg1", "MWTrader", "LS1", signal);
            }
            catch (Exception myE)
            {

            }
        }

        private void btnSendSignalEx_Click(object sender, EventArgs e)
        {
            try
            {
                KaiTrade.TradeObjects.TradeSignal signal = new KaiTrade.TradeObjects.TradeSignal();
                // note that the name should be left blank if you want the server to allocate the name automatically
                // for enter / exit signals. Otherwise the name *must* match the trigger names on the strategy
                signal.Name = txtSignalName.Text;
                signal.Mnemonic = txtOrdrMnemonic.Text;
                signal.OrdQty = double.Parse(txtQty.Text);
                signal.Side = cboSide.Text;
                signal.OrdType = cboOrderType.Text;
                signal.Price = double.Parse(txtPrice.Text);
                if (chkSignalEnter.Checked)
                {
                    signal.SignalType = KaiTrade.Interfaces.TradeSignalType.enter;
                }
                else
                {
                    signal.SignalType = KaiTrade.Interfaces.TradeSignalType.exit;
                }
                signal.Set = chkSignalSet.Checked;

                K2ServiceSupport.K2ServiceClient.Instance().ProcessTradeSignal(txtOrdrStrategy.Text, DateTime.Now.Ticks.ToString(), "KTStandard", "MWTrader", "LS1", true, signal);


            }
            catch (Exception myE)
            {

            }
        }

        #endregion

       

        #region bars

        /// <summary>
        /// Subscribe to regular prices
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSubscribe_Click(object sender, EventArgs e)
        {
            try
            {
                K2ServiceSupport.K2ServiceClient.Instance().SubscribePrices(txtMnemonic.Text);
            }
            catch (Exception myE)
            {
            }
        }

        /// <summary>
        /// Request bar data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRequestBar_Click(object sender, EventArgs e)
        {
            try
            {
                m_LastBars.Clear();
                DateTime start = new DateTime(2011, 2, 1);
                start = dateTimePicker1.Value;
                int number = int.Parse(txtDuration.Text);
                K2ServiceSupport.K2ServiceClient.Instance().GetBars(txtMnemonic.Text, chkUpdates.Checked, start, number, cboPeriod.Text);
            }
            catch (Exception myE)
            {
            }
        }

        /// <summary>
        /// Call back when bars arrive
        /// </summary>
        /// <param name="id"></param>
        /// <param name="requestId"></param>
        /// <param name="mnemonic"></param>
        /// <param name="tsdUpdate"></param>
        void OnTsdUpdate(string id, string requestId, string mnemonic, KaiTrade.TradeObjects.TSDataItem[] tsdUpdate)
        {
            try
            {
                foreach (KaiTrade.TradeObjects.TSDataItem item in tsdUpdate)
                {
                    m_LastBars.Add(item);
                }
            }
            catch (Exception myE)
            {
            }

        }


        /// <summary>
        /// Call back when prices update
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pxUpdate"></param>
        public void OnPxUpdate(string id, KaiTrade.TradeObjects.PXUpdateBase pxUpdate)
        {
            try
            {
                if(pxUpdate.BidPrice.HasValue)
                {
                    SetBidPrice(pxUpdate.BidPrice.ToString());
                }
            }
            catch (Exception myE)
            {
            }

        }

        

        public void SetBidPrice(string text)
        {
            if (txtBidPx.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetBidPrice);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                txtBidPx.Text = text;
            }
        }

        private string tsBar2String(KaiTrade.TradeObjects.TSDataItem tsDataItem)
        {
            string ret = "";
            ret += string.Format("Index {2} Open {0} Close{1} ",  tsDataItem.Open, tsDataItem.Close, tsDataItem.TimeStamp);
            return ret;
        }

        private void btnGetBarData_Click(object sender, EventArgs e)
        {
            try
            {
                
                lstBars.Items.Clear();
                foreach (KaiTrade.TradeObjects.TSDataItem tsDataItem in m_LastBars)
                {
                    lstBars.Items.Add(tsBar2String( tsDataItem));
                }
                
            }
            catch (Exception myE)
            {
            }
        }
        #endregion

       
      

      

       
       

       
        
        
    }
}
